import React, { useEffect, useState } from 'react'
import { message, Table, Tag } from 'antd'
import { getRoleList } from '../../../request/setting'
import { ROLE_AGENT, ROLE_CUSTOMER_SERVICE, ROLE_ADMIN } from '../../../constants'

const roleDescription = {
  [ROLE_ADMIN]: '拥有全部权限',
  [ROLE_CUSTOMER_SERVICE]: '可查看订单列表全部订单（下单套餐、用户来源不可见）',
  [ROLE_AGENT]: '可查看订单列表所属商品（下单套餐）的全部订单'
}

function Role() {
  const [roleList, setRoleList] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [totalCount, setTotalCount] = useState(0)
  const [currentPage, setCurrentPage] = useState(0)
  const pageSize = 30

  useEffect(() => {
    getData().catch(e => console.log(e.message))
  }, [])

  const getData = async(page = 1) => {
    setIsLoading(true)
    const { code, message: errMsg, data } = await getRoleList({ page, size: pageSize })
    setIsLoading(false)
    if (code) {
      return message.error(errMsg)
    }
    setTotalCount(data.total_result)
    setCurrentPage(page)
    setRoleList(data.list)
  }

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      render: (text) => (<span>{text}</span>)
    },
    {
      title: '角色名称',
      dataIndex: 'name'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: text => (text ? <Tag color="green">可用</Tag> : <Tag color="volcano">警用</Tag>)
    },
    {
      title: '描述',
      render: (text, record) => (<span>{roleDescription[record.id] || '-'}</span>)
    }
  ]

  return (
    <div className="user-list">
      <Table
        rowKey={row => row.id}
        loading={isLoading}
        columns={columns}
        dataSource={roleList}
        onChange={page => getData(page.current)}
        pagination={{
          defaultCurrent: 1,
          current: currentPage,
          total: totalCount,
          pageSize,
          showTotal: total => `共 ${total} 条`
        }}
      />
    </div>
  )
}

export default Role
